<template>

  <el-tabs
  >

    <el-tab-pane label="按区域统计水环境计算结果" name="first">
      <el-button type="primary" text='primary' @click="drawPolygon" class="AllButton">
        <el-icon><Edit /></el-icon>绘制统计多边形
      </el-button>
      <el-button type="primary" text='primary' @click="removeDrawLayer" class="AllButton">
        <el-icon><Delete /></el-icon>清除绘制
      </el-button>
      <el-button type="primary" text='primary' @click="cancelDrawLayer" class="AllButton">
        <el-icon><Delete /></el-icon>取消绘制
      </el-button>
      <el-button type="primary" text='primary' @click="showRegionResult" class="AllButton">
        <el-icon><Connection /></el-icon>提交绘制结果统计水环境容量
      </el-button>
    </el-tab-pane>

    <el-tab-pane label="水质统计展示" name="fourth">
      <el-button type="primary" text='primary' @click="drawPolygon" class="AllButton">
        <el-icon><Edit /></el-icon>上传水质监测点数据
      </el-button>
      <el-button type="primary" text='primary' @click="removeDrawLayer" class="AllButton">
        <el-icon><Delete /></el-icon>插值统计河流水质分布
      </el-button>
    </el-tab-pane>



    <el-tab-pane label="共享" name="second">
      <el-button type="primary" text='primary' @click="exportMapAsImage" class="AllButton">
        <el-icon><TopRight /></el-icon>地图导出
      </el-button>

      <el-button type="primary" text='primary' @click="toggleFullScreen" class="AllButton">
        <el-icon><TopRight /></el-icon>切换全屏
      </el-button>
      <el-button type="primary" text='primary' @click="reloadPage" class="AllButton">
        <el-icon><TopRight /></el-icon>刷新
      </el-button>

      <el-upload
          class="shapefile-upload"
          ref="upload"
          action="string"
          :file-list="uploadFiles"
          :auto-upload="true"
          :on-progress="importSubmit"
          multiple="multiple"
          accept=".zip"
      >
        <div>
          <el-button
              type="primary" text='primary'
              slot='trigger'
              class="chaxuns fontSizes AllButton">
            <el-icon><Upload /></el-icon>
            上传河网矢量SHP压缩包
          </el-button>
        </div>
      </el-upload>



<!--      <el-button type="primary" text='primary'-->
<!--                 @click="handleDownload"-->
<!--                 class="AllButton"-->
<!--                 slot='trigger'-->
<!--                 >-->
<!--        <el-icon><Download /></el-icon>-->
<!--        下载河道勘测模板文件-->
<!--      </el-button>-->

<!--      <el-upload-->
<!--          class="shapefile-upload"-->
<!--          ref="upload"-->
<!--          action="string"-->
<!--          :file-list="uploadFiles"-->
<!--          :auto-upload="true"-->
<!--          :on-progress="importSubmitXLSX"-->
<!--          multiple="multiple"-->
<!--          accept=".xlsx,.zip"-->
<!--      >-->
<!--        <div>-->
<!--          <el-button-->
<!--              type="primary" text='primary'-->
<!--              slot='trigger'-->
<!--              class="chaxuns fontSizes AllButton">-->
<!--            <el-icon><Upload /></el-icon>-->
<!--            上传河道地勘测量EXCEL-->
<!--          </el-button>-->
<!--        </div>-->
<!--      </el-upload>-->

<!--      上传监测SHP压缩包-->
      <el-upload
          class="shapefile-upload"
          action="string"
          :auto-upload="true"
          :on-progress="monitorDataUpload"
          accept=".zip"
      >
        <div>
          <el-button
              type="primary" text='primary'
              class="chaxuns fontSizes AllButton">
            <el-icon><Upload /></el-icon>
            上传水质监测SHP压缩包
          </el-button>
        </div>
      </el-upload>

    </el-tab-pane>



    <el-tab-pane label="统计" name="third">
      <el-button
          type="primary" text='primary'
          @click="showCalResult"
          class="AllButton">
        <el-icon><SwitchButton />
        </el-icon>展示水环境容量计算结果
      </el-button>


      <el-button
          type="primary" text='primary'
          @click="Interpolation"
          class="AllButton">
        <el-icon><SwitchButton /></el-icon>水质监测点插值
      </el-button>


    </el-tab-pane>




  </el-tabs>
  <!-- 顶部工具栏 ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ -->

  <!-- 页面内容 ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ -->
  <div class="vue-split-container" style="margin-top: 8px;">

    <!-- 分为15%左侧图层列表、65%地图展示+表格、20%分析结果 ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ -->
    <SplitWrapper :sizes="[10, 65, 25]" :minSize="0" class="vue-split horizontal">
      <!-- 15%左侧图层列表 -->
      <SplitItem class="vue-split-item">
        <div class="vue-split-content nested-content-1" id="layerControl">
          <div class="title layersItem">
            图层列表
          </div>
          <el-divider />
          <ul id="layerTree" class="layerTree"></ul>
        </div>
      </SplitItem>

      <!-- 65%:地图展示70%+表格30% ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ -->
      <SplitItem class="vue-split-item map-container" >
        <SplitWrapper :sizes="[60, 40]" :minSize="0" direction="vertical" class="vue-split vertical map-container">
          <!-- 地图展示70% -->
          <SplitItem class="vue-split-item map-container" >
            <div class="vue-split-content nested-content-2 map-container">
              <!-- this.$refs.map -->
              <ol-map
                  ref="map"
                  id="map"
                  :loadTilesWhileAnimating="true"
                  :loadTilesWhileInteracting="true"
                  :style="mapstyle"
                  @click="mapclick"
                  class="map-border"
              >
                <ol-view
                    ref="view"
                    :center="center"
                    :rotation="rotation"
                    :zoom="zoom"
                    :projection="projection"
                    maxZoom="16"

                />


<!--                <ol-tile-layer title="河流">-->
<!--                  <ol-source-tile-wms-->
<!--                      :url="proxy.$getFullUrl('/geoserver/zzmserver/wms')"-->
<!--                      layers="zzmserver:river"-->
<!--                      serverType="geoserver"-->
<!--                      :transition="0"-->
<!--                      :params="{-->
<!--                      SERVICE: 'WMS',-->
<!--                      VERSION: '1.1.0',-->
<!--                      REQUEST: 'GetMap',-->
<!--                      FORMAT: 'image/png',-->
<!--                      TRANSPARENT: true,-->
<!--                      tiled: true,-->
<!--                      STYLES: '',-->
<!--                      exceptions: 'application/vnd.ogc.se_inimage',-->
<!--                      CRS: 'EPSG:3857',-->
<!--                      WIDTH: 768,-->
<!--                      HEIGHT: 374,-->
<!--                      }"-->
<!--                  />-->
<!--                </ol-tile-layer>-->

                <ol-tile-layer title="底图">
                  <ol-source-tile-wms
                      :url="proxy.$getFullUrl('/geoserver/zzmserver/wms')"
                      layers="zzmserver:shunde"
                      serverType="geoserver"
                      :transition="5"
                      :params="{
                                SERVICE: 'WMS',
                                VERSION: '1.3.0',
                                REQUEST: 'GetMap',
                                FORMAT: 'image/png',
                                TRANSPARENT: true,
                                tiled: true,
                                STYLES: '',
                                exceptions: 'application/vnd.ogc.se_inimage',
                                CRS: 'EPSG:3857',
                                }"
                  />
                </ol-tile-layer>
                <!-- 河流 -->
                <!--                水质监测点-->
<!--                <ol-tile-layer title="水质监测点">-->
<!--                  <ol-source-tile-wms-->
<!--                      :url="proxy.$getFullUrl('/geoserver/zzmserver/wms')"-->
<!--                      layers="zzmserver:rivermonitor"-->
<!--                      serverType="geoserver"-->
<!--                      :transition="0"-->
<!--                      :params="{-->
<!--                                        SERVICE: 'WMS',-->
<!--                                        VERSION: '1.1.0',-->
<!--                                        REQUEST: 'GetMap',-->
<!--                                        FORMAT: 'image/png',-->
<!--                                        TRANSPARENT: true,-->
<!--                                        tiled: true,-->
<!--                                        STYLES: '',-->
<!--                                        exceptions: 'application/vnd.ogc.se_inimage',-->
<!--                                        CRS: 'EPSG:3857',-->
<!--                                        WIDTH: 768,-->
<!--                                        HEIGHT: 374,-->
<!--                                        }"-->
<!--                  />-->
<!--                </ol-tile-layer>-->
                <!-- 边界 -->
<!--                <ol-tile-layer title="边界">-->
<!--                  <ol-source-tile-wms-->
<!--                      :url="proxy.$getFullUrl('/geoserver/zzmserver/wms')"-->
<!--                      layers="zzmserver:RiverBoundary"-->
<!--                      serverType="geoserver"-->
<!--                      :transition="0"-->
<!--                      :params="{-->
<!--                                        SERVICE: 'WMS',-->
<!--                                        VERSION: '1.1.0',-->
<!--                                        REQUEST: 'GetMap',-->
<!--                                        FORMAT: 'image/png',-->
<!--                                        TRANSPARENT: true,-->
<!--                                        tiled: true,-->
<!--                                        STYLES: '',-->
<!--                                        exceptions: 'application/vnd.ogc.se_inimage',-->
<!--                                        CRS: 'EPSG:3857',-->
<!--                                        WIDTH: 768,-->
<!--                                        HEIGHT: 371,-->
<!--                                        }"-->
<!--                  />-->
<!--                </ol-tile-layer>-->
                                <!-- 点击按钮来放大或缩小地图的视图 -->
                <ol-zoom-control />
                <ol-interaction-select
                    @select="featureSelected"
                    :condition="selectCondition"
                    :filter="selectInteactionFilter"
                >
                  <ol-style>
                    <ol-style-stroke color="green" :width="10"></ol-style-stroke>
                    <ol-style-fill color="rgba(255,255,255,0.5)"></ol-style-fill>
                  </ol-style>
                </ol-interaction-select>


<!--                <ol-overlay-->
<!--                    :position="selectedCityPosition"-->
<!--                    v-if="selectedCityName != ''"-->
<!--                >-->
<!--                  <template v-slot="slotProps">-->
<!--                    <div class="overlay-content">-->
<!--                      {{ selectedCityName }} {{ slotProps }}-->
<!--                    </div>-->
<!--                  </template>-->
<!--                </ol-overlay>-->

              </ol-map>
              <!-- map ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ -->


            </div>
          </SplitItem>

          <!-- 表格30% -->
          <SplitItem class="vue-split-item">
            <div class="vue-split-content nested-content-2 table-container">
                <riverAttributesForm></riverAttributesForm>
            </div>
          </SplitItem>
        </SplitWrapper>
      </SplitItem>
      <!-- 65%:地图展示70%+表格30% ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ -->

      <!-- 20%分析结果 -->
      <SplitItem class="vue-split-item">
        <div class="vue-split-content nested-content-1 analysis">
          <toolbar
              @clickChild = "clickEven">
          </toolbar>
          <div class="container">
<!--            <NumericInputField-->
<!--                v-if="result === '基本参数'"-->
<!--            />-->
            <!--        class="floating-input"-->

            <calculationMethod
                v-if="result === '计算方法'"
            ></calculationMethod>
            <riverenvanlysis
                v-if="result === '结果分析'"
            >
            </riverenvanlysis>
            <riverprofile
              v-if ="result === '河道剖面'">

          </riverprofile>
            <attri-popup
              :properties ="properties"
              v-if ="result === '属性表'">
            </attri-popup>
            <total-env-by-region
                v-if ="result === '按区域统计结果'"
                :RegionResult ="RegionResult"
            >

            </total-env-by-region>

            <!--    <riverAttributesForm />-->
<!--            <translationInputField-->
<!--                v-if ="result === '坐标转换参数'"-->
<!--            >-->

<!--            </translationInputField>-->
          </div>
        </div>
      </SplitItem>
    </SplitWrapper>

<!--    <div id="app">-->
<!--      <el-table :data="featuresData">-->
<!--        <el-table-column prop="rivername" label="河道名称"></el-table-column>-->
<!--        <el-table-column prop="designflow" label="设计流量"></el-table-column>-->
<!--        <el-table-column prop="wide" label="河道宽度（m）"></el-table-column>-->
<!--        &lt;!&ndash; 更多列... &ndash;&gt;-->
<!--      </el-table>-->
<!--    </div>-->

  </div>
   页面内容 ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
</template>


<script setup lang="ts">
import {PostWKT} from "@/utils/PostWKT.js"
import AttriPopup from "@/components/RiverEnv/Popup.vue"
import { WKT } from 'ol/format.js';
import * as interaction from 'ol/interaction';
import riverprofile from "@/components/RiverProfile.vue"
import {handleDownload} from "@/utils/handleDownload.js"
import toolbar from "@/components/RiverEnv/RiverEnvToolBar.vue"
import 'ol/ol.css';
import riverAttributesForm from '@/components/RiverEnv/riverAttributesForm.vue';
import {FullScreen, ScaleLine} from "ol/control";
import {getCurrentInstance, inject, onMounted, reactive, ref} from "vue";
import {ElButton, ElIcon, ElMessage} from 'element-plus';
import * as ol from 'ol';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-quartz.css";
import Draw from 'ol/interaction/Draw.js';
import {Vector as VectorSource2} from 'ol/source.js';
import {Vector as VectorLayer2} from 'ol/layer.js';
import {Get, Post, PostFile} from "@/axios/api";
import {Connection, Delete, Edit, SwitchButton, TopRight, Upload,} from '@element-plus/icons-vue';
import {SplitItem, SplitWrapper} from 'vue3-split';
import 'ol-layerswitcher/dist/ol-layerswitcher.css';
import LayerSwitcher from 'ol-layerswitcher';
import * as XLSX from 'xlsx';
// import NumericInputField from "@/components/RiverEnv/numericInputField.vue";
import calculationMethod from "@/components/RiverEnv/calculationMethod.vue"
import riverenvanlysis from "@/components/RiverEnv/RiverEnvAnalysisResults.vue"
import {Stroke, Style} from "ol/style";
import {GeoJSON} from "ol/format";
import {s} from "vite/dist/node/types.d-aGj9QkWt";
import * as url from "url";
import {log} from "echarts/types/src/util/log";
import TileLayer from "ol/layer/Tile";
import TotalEnvByRegion from "@/components/RiverEnv/totalEnvByRegion.vue";

const result=ref('')
const clickEven= val =>{
  console.log(val);
  result.value=val
}



// 河槽蓄水量
const riverStorageVolume = ref()

const handleClick = (tab) => {
  // activeTabName.value = tab.props.label; // Update the activeTabName with the clicked tab's name
  // ElMessage.success(`切换到：${tab.props.label}`); // Optional: Show a success message indicating the active tab
  //传递给父组件
  emit('clickChild',tab.props.label)

}
// const layerSwitcher = new LayerSwitcher();

const {proxy} = getCurrentInstance()

const screenWidth = ref(document.documentElement.clientWidth);//实时屏幕宽度
const screenHeight = ref(document.documentElement.clientHeight);//实时屏幕高度


const mapstyle=ref("width: "+(screenWidth.value-204)+"px;height: "+(screenHeight.value-350)+"px")



const rowData = ref([
  { make: "Tesla", model: "Model Y", price: 64950, electric: true },
  { make: "Ford", model: "F-Series", price: 33850, electric: false },
  { make: "Toyota", model: "Corolla", price: 29600, electric: false },
]);

// Column Definitions: Defines the columns to be displayed.
const colDefs = ref([
  { field: "make" },
  { field: "model" },
  { field: "price" },
  { field: "electric" }
]);



(function() {
  // function body
  console.log('立即执行函数')
})();




const selectedCityName = ref("");
const selectedCityPosition = ref([]);
const drawEnable = ref(false);

const format = inject("ol-format");
const geoJson = new format.GeoJSON();

const selectConditions = inject("ol-selectconditions");
const selectCondition = selectConditions.pointerMove;

//const selectConditions = inject("ol-events-conditions");
//const selectCondition = selectConditions.singleClick;

const selectInteactionFilter = (feature) => {
  console.log(feature);
  return feature.values_.burytype != undefined;
};

const modelSatus = reactive({
  status: true,
});
const form = reactive({
  input: "",
  list: {},
});
const mapClickData = reactive({
  input: "",
  list: {},
});
const mapRightData = reactive({
  input: "",
  list: {},
});
//const center = ref([40, 40]);
const projection = ref("EPSG:3857");
const zoom = ref(12);
const rotation = ref(0);
//const size = ref([1024, 968]);
//const center = ref([size.value[0] / 2, size.value[1] / 2]);
const center =ref([12605523,2613832]);
//const size = ref([12605523*2, 2613832*2]);
//const extent = ref([0, 0, ...size.value]);
const extent = inject("ol-extent");


const featureSelected = (event) => {
  console.log(event);
  console.log(event.selected);
  if (event.selected.length == 1) {
    selectedCityPosition.value = extent.getCenter(
        event.selected[0].getGeometry().extent_,
    );
    //selectedCityName.value = event.selected[0].values_.name;
    selectedCityName.value = event.selected[0].values_.burytype;
  } else {
    selectedCityName.value = "";
  }
};

const zone_name=ref("");
const childRef = ref(null);

function featureClicked(event) {
  console.log("featureClicked");
  console.log(event);
  console.log(event.target.value)
}
const featuredata = ref()

// function mapclick(event){
//   ElMessage("点击位置"+event.coordiate)
//   var feature = event.map.forEachFeatureAtPixel(event.pixel, function (feature) {
//     return feature;
//   });
//   ElMessage(feature)
//   if(feature){
//     featuredata.value = feature.values_
//     console.log("featuredata.value"+featuredata.value);
//     //mapClickData.input=feature.values_.burytype;
//     mapClickData.list=feature.values_;
//     console.log(mapClickData.list);
//     //console.log(mapClickData.list.zone_name);
//     zone_name.value=feature.values_.zone_name;
//     //if (childRef.value) {
//     childRef.value.childMethod(zone_name.value);
//     childRef.value.childSelMethod(mapClickData.list);
//     //}
//   }
// }

const uploadFiles = ref([]);
const map = ref(null);


//------------------------添加地图---------------------------------------
//------------------------添加地图---------------------------------------
//------------------------添加地图---------------------------------------
//------------------------添加地图---------------------------------------
// 创建 GeoJSON 格式解析器
const geojsonformat = new GeoJSON();

// 创建一个 VectorSource 并加载 GeoJSON 数据
const riverSource = new VectorSource({
  url:proxy.$getFullUrl('/geoserver/zzmserver/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=zzmserver%3Ariver&outputFormat=application%2Fjson'),
  // url: '/geoserver/zzmserver' +
  //     '/ows?service=WFS&version=1.0.0&request=GetFeature&' +
  //     'typeName=zzmserver%3Ariver&maxFeatures=50&outputFormat=application%2Fjson', // GeoJSON 文件的 URL
  format: geojsonformat
});

// 创建 GeoJSON 格式解析器
const RiverEnvgeojsonformat = new GeoJSON();

const moniterSource = new VectorSource({
  url:proxy.$getFullUrl('/geoserver/zzmserver/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=zzmserver%3Arivermonitor&outputFormat=application%2Fjson'),
  // url: '/geoserver/zzmserver' +
  //     '/ows?service=WFS&version=1.0.0&request=GetFeature&' +
  //     'typeName=zzmserver%3Ariver&maxFeatures=50&outputFormat=application%2Fjson', // GeoJSON 文件的 URL
  format: RiverEnvgeojsonformat
});

// 水环境计算结果图层
const riverenvresultSource = new VectorSource({
  url:proxy.$getFullUrl('/geoserver/zzmserver/ows' +
      '?service=WFS&version=1.0.0&request=GetFeature' +
      '&typeName=zzmserver' +
      '%3Awaterenvironmentcapacityresult' +
      '&outputFormat=application%2Fjson'),
  // url: '/geoserver/zzmserver' +
  //     '/ows?service=WFS&version=1.0.0&request=GetFeature&' +
  //     'typeName=zzmserver%3Ariver&maxFeatures=50&outputFormat=application%2Fjson', // GeoJSON 文件的 URL
  format: geojsonformat,
});



// // 水环境计算结果图层
// const riverenvresultSource = new VectorSource({
//   url:"http://localhost:9602/getRiverEnvGeoJson/facfb9b3-b2a5-4cd9-80ff-454fddce46eb",
//
//   format: geojsonformat,
// });
// const riverSourceData=ref(null);
// const GetData = () => {  Get("http://localhost:8010/geoserver/zzmserver/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=zzmserver%3Awaterenvironmentcapacityresult&maxFeatures=50&outputFormat=application%2Fjson",{}).then((response) => {
//   const { code, msg, features: res } = response.data;
//   // if (code === 200) {
//   console.log("features:"+res);
//     riverSourceData.value = res;
//   // }
// });}
//
// // 水环境计算结果图层
// const riverenvresultSource = new VectorSource({
//   features: new GeoJSON().readFeatures(riverSourceData.value)
// });

// 河流图层
const rivervectorLayer = new VectorLayer({
  properties: {title:'河流'},
  source: riverSource,
  style: new Style({
    stroke: new Stroke({
      color: '#303b4c',
      width: 2
    })
  })
})


const styleFunction = function(feature) {
  let cod = feature.get('cod');

  // 确定cod的最小最大值，这里假定为minCod和maxCod
  // 实际应用中，你可能需要从数据集中计算出这些值
  const minCod = 0; // 示例最小值
  const maxCod = 150; // 示例最大值

  // 计算每一份的边界值
  const step = (maxCod - minCod) / 5;

  if (cod <= minCod + step) {
    return new Style({
      stroke: new Stroke({
        color: '#3381ff',
        width: 1,
      })
    });
  } else if (cod <= minCod + 2 * step) {
    return new Style({
      stroke: new Stroke({
        color: '#33e4ff', // 绿色
        width: 1,
      })
    });
  } else if (cod <= minCod + 3 * step) {
    return new Style({
      stroke: new Stroke({
        color: '#33fcff', // 橙色
        width: 1,
      })
    });
  } else if (cod <= minCod + 4 * step) {
    return new Style({
      stroke: new Stroke({
        color: '#d9534f', // 红色
        width: 1,
      })
    });
  } else {
    return new Style({
      stroke: new Stroke({
        color: '#e53a3a', // 蓝绿色
        width: 1,
      })
    });
  }
}

const riverenvresultSource0 = new VectorSource({
  // url:'http://1.1.1.200:9602/River/mockgeoserver',

  format: geojsonformat,
});

// 创建一个 VectorLayer 并关联 VectorSource
const riverEnvResultLayer = new VectorLayer({
  source: riverenvresultSource0,
  style: styleFunction
});



// 创建一个 VectorLayer 并关联 VectorSource
// const rivermonitorLayer = new VectorLayer({
//   source: moniterSource,
//   title: '水质监测点',
//   // style: new Style({
//   //   image: new CircleStyle({
//   //     radius: 7, // 圆形点的半径
//   //     fill: new Fill({
//   //       color: 'rgba(255, 0, 0, 0.8)' // 填充颜色
//   //     })
//   //   })
//   // })
// });
//------------------------添加地图---------------------------------------
//------------------------添加地图---------------------------------------
//------------------------添加弹窗---------------------------------------
// 创建一个div
let div_popup;
function createPopupDiv(){
  div_popup=document.createElement('div');
  div_popup.id="_popup";
  // div_popup.className="popup";
  div_popup.style.cssText ="" +
      "display:block;" +
      "background:white;" +
      "color:black;" +
      "border:solid 1px;" +
      "width:200px;"+
      "height:200px;" +
      "margin-left: 40px;" +
      "margin-top:20px;"
  document.body.appendChild(div_popup);
}
createPopupDiv();
// 创建一个overlay层
let _popup = new ol.Overlay({
  element: document.getElementById('_popup'),
  autoPan: false, // 关闭自动平移，因为我们自己控制位置
  stopEvent: false, // 防止事件冒泡
  // offset:[5,-5]
});

let selectClick = new interaction.Select()

//------------------------添加弹窗---------------------------------------





//比例尺控件
// 创建比例尺控件
const scaleLine = new ScaleLine({
  units: 'metric', // 可以是 'us' 或 'nautical'，默认是 'metric'
  bar: true,       // 是否显示比例尺条
  steps: 2,        // 比例尺条的数量
  text: true,      // 是否显示数字文本
  minWidth: 80    // 比例尺的最小宽度
});
//------------------------图层切换控件---------------------------------------
// 创建一个图层切换控件
const layerSwitcher = new LayerSwitcher({
  reverse:true,// 图层按顺序展示
});

// let xxx = document.getElementById('layers')

//------------------------图层切换控件---------------------------------------

// 初始化数据，存储弹窗中哪些字段来展示
const properties = ref({});

onMounted(() => {

  setTimeout(function() {
    var allElements = document.getElementsByTagName('div');
    for(var i = 0; i < allElements.length; i++) {
      if (allElements[i].classList.contains('gutter')) {
        // 添加到结果数组中
        allElements[i].setAttribute("style", "background-color: #ebebeb; font-size: 12px;width: 10px;");
      }
    }
  }, 1000);




  // addPopup(); //弹窗
  map.value.map.addControl(scaleLine); //添加比例尺
  // map.value.map.addInteraction(selectInteraction);
  map.value.map.addLayer(vectorDraw);
  map.value.map.addControl(new FullScreen());
  map.value.map.addLayer(rivervectorLayer);//添加河流地图
  // map.value.map.addLayer(rivermonitorLayer);//添加水质监测点
  map.value.map.addControl(layerSwitcher);//添加图层切换控件
  // LayerSwitcher.renderPanel(map.value.map,xxx,{ reverse: true })
  map.value.map.addInteraction(selectClick)
  //点击出现弹窗，查询各个图层的属性
  selectClick.on('select', function(e) {
    let features=e.target.getFeatures().getArray();
    if(features.length>0){
      let element = _popup.getElement();
      let coor=features[0].getGeometry().getCoordinates();
      // 从 Feature 的 values_ 对象中获取所有属性

      // 获取所有属性,传递给另一个组件
      properties.value = features[0].values_;


      _popup.setPosition(coor);
    }else{
      // map.value.map.removeOverlay(_popup);
    }
  })
  //显示图层数量
  showTreeLayers();
  // 聚焦河流图层
  console.dir(map.value.map)

});




// 展示哪一个水位的水环境计算结果
let whichHeadtoShow = ref(null)


/**
 * 点击展示水环境容量计算结果再进行加载图层操作
 */
const showCalResult = async () => {
  try {

    whichHeadtoShow.value = parseFloat(prompt("请输入一个水位来展示水环境计算结果"))

    // 确保whichHeadtoShow有值
    if (whichHeadtoShow.value === null) {
      ElMessage.warning("请选择一个水位来展示水环境计算结果。");

      return;
    }

    const response = await Get('/River/getRiverEnvGeoJson/'+whichHeadtoShow.value, {});
    const { code, msg, data: res } = response.data;
    if (code === 200) {
      ElMessage.success(msg ?? "拉取GeoJSON");
      // 这里你可以将res赋值给geojsonData
      const geojsonData = res;

      const riverEnvSource = new VectorSource({
        features: new GeoJSON().readFeatures(geojsonData),
      });

      const riverEnvResultLayer = new VectorLayer({
        source: riverEnvSource,
        style: styleFunction,
      });
      // 现在你可以使用geojsonData来加载图层
      map.value.map.addLayer(riverEnvResultLayer);
    } else {
      ElMessage.error("拉取失败"+msg);
    }
  } catch (error) {
    ElMessage.error("请求错误：" + error.message);
  }
};



const drawSource = new VectorSource2({wrapX: false});

const vectorDraw = new VectorLayer2({
  source: drawSource,
});

//全局变量，用于存储地图绘制和绘制交互
let draw = new Draw({
  source: drawSource,
  type: 'Polygon',
})  // global so we can remove it later


// 添加绘制的图形
function drawPolygon(){
  map.value.map.addInteraction(draw);
}


function removeDrawLayer(){
  // 移除绘制交互
  const source = vectorDraw.getSource();
  const lastFeature = source.getFeatures().pop(); // 获取最后一个特征
  if (lastFeature) {
    source.removeFeature(lastFeature); // 将其删除
  }
}

//拿到绘制图形的WKT
function getWKT(){
  const source = vectorDraw.getSource();
  const lastFeature = source.getFeatures().pop() // 获取最后一个特征
  const wkt = new WKT()
  let postwkt = wkt.writeFeature(lastFeature);
  return postwkt
}




// 水环境计算结果
const RegionResult = ref()

//添加按区域统计的水环境计算结果
const showRegionResult = async ()=>{
  //拿到WKT
  let wkt = getWKT()
  //发送WKT，接收水环境计算结果
  RegionResult.value = await PostWKT(wkt)
  // console.dir(RegionResult.value)
}

// 取消绘制
const cancelDrawLayer = ()=>{
  map.value.map.removeInteraction(draw)
}


function showTreeLayers(){
  // 图层控制
  let layersContent = document.getElementById('layerTree');
  let layers = map.value.map.getLayers();    //获取地图中所有图层
  let layer = [];                   //map中的图层数组
  let layerName = [];               //图层名称数组
  let layerVisibility = [];         //图层可见属性数组
  for (let i = 0; i < layers.getLength()-2 ; i++) {

    layer[i] = layers.item(i);
    layerName[i] = layer[i].get('title');
    layerVisibility[i] = layer[i].getVisible();

    let eleLi = document.createElement('li');           //新增li元素，用来承载图层项
    eleLi.setAttribute('style', 'font-size: 12px; margin-top: 4px;');
    let eleInput = document.createElement('input');     //创建复选框元素，用来控制图层开启关闭
    eleInput.setAttribute('style', 'font-size: 12px; margin-right: 8px;');
    eleInput.type = "checkbox";
    eleInput.name = "layers";
    eleLi.appendChild(eleInput);                        //将复选框添加到li元素中

    layersContent.insertBefore(eleLi,layersContent.childNodes[1]); //将li元素作为子节点放入到图层目录中（按图层加载倒序0,顺序1）
    let eleLable = document.createElement('label');     //创建label元素
    setInnerText(eleLable, layerName[i]);                //在label中设置图层名称
    eleLi.appendChild(eleLable);                         //将label加入到li中

    if (layerVisibility[i]) {                            //设置图层默认显示状态
      eleInput.checked = true;
    }
    addChangeEvent(eleInput, layer[i]);              //为checkbox添加变更事件
  }
}






function setInnerText(element, text) {
  if (typeof element.textContent == "string") {
    element.textContent = text;
  } else {
    element.innerText = text;
  }
}

/*
* 为checkbox元素绑定变更事件
*/
function addChangeEvent(element, layer) {
  element.onclick = function () {
    if (element.checked) {
      //显示图层
      layer.setVisible(true);
    }
    else {
      //不显示图层
      layer.setVisible(false);
    }
  };
}






async function importSubmit (filerow,url = '/River/riverShpUpload') {

  const file=filerow.raw;
  let data = await uploadZip(file, url);
  console.log("后端返回的geojson"+data)
  return data

}

// 上传水质监测点得到的UUID
const time = ref()

//上传河道水质监测点
function monitorDataUpload(e,filerow){
  const formData=new FormData();
  formData.append("shapefile",filerow.raw);
  PostFile('/River/monitorDataUpload',formData).then((response) => {
    const { code, msg,data:res } = response.data;
    if (code === 200) {
      // 接收返回的水质监测点geojson
      time.value = msg
      let readFeatures = new GeoJSON().readFeatures(res)
      //创建水质监测图层，设置title
      const monitorSourceLayer = new VectorLayer({
        properties: {title:'监测点'},
        source: new VectorSource({
          features: readFeatures,}),
      })
      // 加载图层
      map.value.map.addLayer(monitorSourceLayer);
      // 调整视图范围,缩放至要素范围
      map.value.map.getView().fit(monitorSourceLayer.getSource().getExtent(), { duration: 2 });
    } else {
      ElMessage.error("上传出现意外")
    }
  });
}

const Interpolation =async ()=>{
  // 请求后端进行水质插值计算
  await Post('/River/RiverInterpolation',{"time":time.value}).then((response) => {
    const { code, msg,data: res } = response.data;
    if (code === 200) {
      let readFeatures = new GeoJSON().readFeatures(res)
      //创建水质监测图层，设置title
      const waterQualityLayer = new VectorLayer({
        properties: {title:'河道水质'},
        source: new VectorSource({
          features: readFeatures,}),
      })
      // 加载图层
      map.value.map.addLayer(waterQualityLayer);
      // 调整视图范围,缩放至要素范围
      map.value.map.getView().fit(waterQualityLayer.getSource().getExtent(), { duration: 2 });
    } else {
      ElMessage.error("插值失败");
    }
  })
}


const rightChildRef = ref(null);

function showFeaturesMap(features) {
  const vectorSource = new VectorSource({ features: features});
  // vectorSource.addFeatures(features);
  // 创建矢量图层并添加到地图
  const vectorLayer = new VectorLayer({
    source: vectorSource,
    // 设置样式
  });

  if (map) {
    map.value.map.addLayer(vectorLayer);
  }

}


function uploadShpGeoJSON(geometryArray) {
  let shpArray=geometryArray.join('');
  console.log("shpArray:"+shpArray);
  Post('/Pollution/acceptShp',geometryArray).then((response) => {
    console.log("response.data:"+response.data);
    const { code, msg,data: res } = response.data;
    if (code === 200) {
      console.log("上传结束:"+res);
      mapRightData.list=res;
      rightChildRef.value.childSelMethod(mapRightData.list);
      ElMessage.success(msg ?? "Submitted!");
    } else {
      //ElMessage.error(msg);
      ElMessage.error("提交失败");
    }
  });
}


//解析一个coordinates为字符串 {type: 'Polygon', coordinates: Array(1)}
function getPointStr(coordinates){
  let pointArray = "";
  let stringsArray = [];
  for(let i = 0; i < coordinates.length; i++) {
    //console.log(coordinates[i]);
    //pointArray=pointArray+"["+coordinates[i]+"]";
    if(i!=coordinates.length-1)
      stringsArray.push(""+coordinates[i]+",");
    else
      stringsArray.push(""+coordinates[i]+"");
    //console.log("stringsArray:"+stringsArray);
  }
  pointArray=stringsArray.join('');
  //console.log("pointArray:"+pointArray);
  return pointArray;
}



function uploadZip(zipFile,s){
  const formData=new FormData();
  formData.append("shapefile",zipFile);
  PostFile(s,formData).then((response) => {
    console.log("zipFile response.data:"+response.data);
    const { code, msg,data: res } = response.data;
    if (code === 200) {
      console.log("success:"+msg+"上传成功"+res.toString());
      // rightChildRef.value.fenquSelMethod(res.geojson.list);
      // rightChildRef.value.fenquMapMethod(res.fenquMap.fenquList);
      ElMessage.success(msg ?? "Submitted!");
      return res
    } else {
      ElMessage.error("上传失败")
    }
  });
      return null
}



// 导出地图为PNG图片
function exportMapAsImage() {
  const mapCanvas = document.createElement('canvas');
  // var canvas =   map.value.map.getCanvas();
  var canvas =   mapCanvas;
  var dataURL = canvas.toDataURL('image/png');
  const ctx = canvas.getContext('2d');

  // 绘制一些图形
  ctx.fillStyle = 'red';
  ctx.fillRect(0, 0, 100, 100);

  // 创建一个a元素用于下载
  var a = document.createElement('a');
  a.href = dataURL;
  a.download = 'map.png';
  a.click();
}

function reloadPage() {
  // 使用Vue Router的reload方法
  // $router.go(0);

  // 或者使用原生JavaScript
  window.location.reload();
}

function toggleFullScreen() {
  if (!document.fullscreenElement) {
    enterFullScreen();
  } else {
    exitFullScreen();
  }
}
function enterFullScreen() {
  let element = document.documentElement;
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) { /* Firefox */
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) { /* IE/Edge */
    element.msRequestFullscreen();
  }
}
function exitFullScreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) { /* Firefox */
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
    document.webkitExitFullscreen();
  } else if (document.msExitFullscreen) { /* IE/Edge */
    document.msExitFullscreen();
  }
}

// let overlay: Overlay =ref(null);
/**
 * Popup 弹窗
 */
// const addPopup = () => {
//   // 使用变量存储弹窗所需的 DOM 对象
//   var container = document.getElementById("popup");
//   var closer = document.getElementById("popup-closer");
//   var content = document.getElementById("popup-content");
//   var detail = document.getElementById("popup-detail");
//   // 创建一个弹窗 Overlay 对象
//   overlay = new Overlay({
//     element: container, //绑定 Overlay 对象和 DOM 对象的
//     autoPan: true, // 定义弹出窗口在边缘点击时候可能不完整 设置自动平移效果
//   });
//   // 将弹窗添加到 map 地图中
//   map.value.map.addOverlay(overlay);
  /**
   * 添加单击响应函数来处理弹窗动作
   */
  // map.value.map.on("click", function (evt) {
  //   var feature = map.value.map.forEachFeatureAtPixel(evt.pixel, function (feature) {
  //     return feature;
  //   }, {
  //     hitTolerance: 5 // 设置点击容差为 5 像素
  //   });
  //
  //   if (feature) {
  //     ElMessage('123'+feature)
  //     let value = feature.get("area");
  //
  //     overlay.setPosition(evt.coordinate); //把 overlay 显示到指定的 x,y坐标
  //
  //   } else {
  //     // ElMessage("空")
  //
  //     overlay.setPosition(undefined);
  //   }
  // });
  /**
   * 为弹窗添加一个响应关闭的函数
   */
  // closer.onclick = function () {
  //   overlay.setPosition(undefined);
  //   closer.blur();
  //   return false;
  // };
  // detail.onclick = function () {
  //   modelSatus.status = true;
  //   overlay.setPosition(undefined);
  // };
// };

function importSubmitXLSX(e,filerow,fileList) {

  const file=filerow.raw;
  uploadXLSX(file);

}

function uploadXLSX(xlsxFile){
  const formData=new FormData()
  formData.append("file",xlsxFile)

  PostFile('/River/uploadRiverMeasurementData',formData).then((response) => {
    const { code, msg,data: res } = response.data;
    if (code === 200) {
      riverStorageVolume.value = res
    } else {
      ElMessage.error(msg+'上传失败');
    }
  });
}

</script>


<style scoped lang="scss">
*{
  padding: 0;
  margin: 0;
  list-style: none;
}
#map{
  // position: absolute;
  width: 100%;
  height: 100%;
}
#layerControl {
  // position: absolute;
  // z-index: 999;
  // width: 200px;
  // height: 300px;
  // background-color: rgba(78, 70, 109, 0.596);
  // left: 50px;
  // top: 200px;
  // padding: 5px;
  // border-radius: 10px;
  // -webkit-border-radius: 10px;
  // -moz-border-radius: 10px;
  // -ms-border-radius: 10px;
  // -o-border-radius: 10px;
}

#layerControl .title {
  color: rgb(0, 0, 0);
  text-align: center;
  font-size: 12px;
  margin: 0px 0px;
}

#layerControl li {
  color: ivory;
}

#layerControl input {
  margin-right: 10px;
}

#layerlistbtn {
  position: fixed;
  right: 15px;
  top: 50px;
}

#map {
  width: 100%;
  height: 100%;
}

.map-container {
  position: relative; /* 或者其它需要的定位方式 */
  width: 100%; /* 保证宽度填满父容器 */
  height: 100px; /* 或者其它适应性高度，如vh单位、Flexbox的flex-grow等 */
}

// .table-container {
//   position: relative; /* 或者其它需要的定位方式 */
//   width: 100%; /* 保证宽度填满父容器 */
//   height: 100px; /* 或者其它适应性高度，如vh单位、Flexbox的flex-grow等 */
// }

.vue-split-container {
  height: 100%;
  // border: 4px dashed rgba(229, 231, 235, 0.4);
  // border-radius: 0.5rem;
}

.vue-split {
  height: 100%;
}

.vue-split.horizontal {
  display: flex;
  flex-direction: row;
}

.vue-split.horizontal .vue-split-content {
  height: 100%;
}
/**/
.gutter {
  // background-color: #ffffff;
  background-color: #030303;
  background-repeat: no-repeat;
  background-position: 50%;
}

.gutter.gutter-horizontal {
  background-image: url('');
  cursor: col-resize;
}

.gutter.gutter-vertical {
  background-image: url('');
  cursor: row-resize;
}

ul#layerTree.layerTree{
  text-indent: -10px;
  // background-color: aqua;
  font-size: 12px;
  margin-left: 16px;
  margin-top: 14px;
  color: #73767a;

}

/*
.gutter {  background-color: #eee;  background-repeat: no-repeat;  background-position: 50%;
  cursor: move;  cursor: grab;  cursor: -moz-grab;  cursor: -webkit-grab;
}.gutter.gutter-horizontal {  background-image: url('grips/vertical.png');
}.gutter.gutter-vertical {  background-image: url('grips/horizontal.png');
}
*/
.vue-split-item {
  height: 100%;
  overflow: hidden;
}

.vue-split-content {
  padding: 8px;
  height: 100%;
  // display: flex;
  align-items: center;
  // justify-content: center;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.nested-content-1,
.nested-content-2,
.toptools {
  background: rgba(247,248,248, .9);
  // border: 1px solid rgb(4,124,195);
}

// .nested-content-2 {
//   background: rgba(247,248,248, .9);
//   border-color: rgb(156,220,252);
// }

// .toptools {
//   background: rgba(247,248,248, .9);
//   border-color: rgb(156,220,252);
// }
// .map-border {
//   // width: 100%;
//   // height: 100%;
//   border: 1px solid #333; /* 根据需要调整边框宽度、颜色和样式 */
//   border-radius: 4px; /* 可选：添加圆角以实现边框圆角化 */
// }
.shapefile-upload{
  display: inline-block;
  margin-left: 12px;
  // display: inline;
  text-align: center;
  cursor: pointer;
  outline: 0;
  // margin-top: 10px;
}
.AllButton{
  font-size: 12px;
  padding: 10px;
}

// 图层列表标题
#layerControl .title{
  font:700 12px/1.5 "Microsoft Yahei",Arial,Helvetica,sans-serif;
  border-color: #79bbff;
  background-color: #79bbff;
  // border-style: solid;
  // border-width: 1px;
  // border-radius: 4px;
  // background-color: #f4f4f5;
  // color: #409EFF;
  color: #ffffff;
  padding-top: 5px;
  padding-bottom: 5px;
  padding-left: 9px;
  text-align: left;
  // box-shadow: 10px 10px 5px -4px rgba(129, 129, 129, 0.603);
  // boxShadow: Dark Shadow;
  // box-shadow: 0 0 5px 0 #d9ecff;
};




.demo-tabs{
  height: 80px;
  width: 100%;
}

.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
}
.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}
.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
  cursor: pointer;
}
.ol-popup-detail {
  text-decoration: none;
  position: absolute;
  top: 4px;
  left: 8px;
  cursor: pointer;
}
.popup {
  width: 200px;
  background-color: #abc2df;
}

#layerTree {
  list-style-type: none;
  padding: 1;
  margin: 0;
  background-color: #ffffff;
  border: 0px solid #dee2e6;
  border-radius: 5px;
}

#layerTree li {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

#layerTree li:hover {
  background-color: rgba(132, 131, 131, 0.76);
}

.layer-switcher {
  position: absolute;
  top: 3.5em;
  right: 0.5em;
  text-align: left;
  left: 10px;
  right: auto;
  top: 4em;
}
</style>